/***********************************************************/
/* Name: Stephen Wiens
/* Student No.: 00324854
/* Course: CPSC4559
/* SB Skype
* Reason: Able to View,Rename, Delete, or Edit a current file here.
/***********************************************************/
package Client;

import SBLib.Clientcheck;
import SBLib.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author StephenWiens
 */
public class File_viewer extends javax.swing.JFrame {

    static User temp = new User(null, null);
    static ObjectOutputStream outToServer;
    static ObjectInputStream inFromServer;
    static String divider = "&&&";
    static String chunks[];
    static int file_type;
    static String Message;
    static String title;
        static Socket clientSocket;

    /**
     * Creates new form File_viewer
     */
    public File_viewer() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        FileNamefeild = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        Contentfeild = new javax.swing.JTextArea();
        Title = new javax.swing.JLabel();
        Error_text = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                jPanel1MouseMoved(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
        jLabel1.setText("File Name:");

        FileNamefeild.setText(".txt");

        jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
        jLabel2.setText("Text Feild:");

        if(file_type == 1 || file_type == 2|| file_type == 3|| file_type ==4)
        {
            Contentfeild.setText(Message);
            if(file_type == 1 || file_type == 2||file_type == 4)
            Contentfeild.setEditable(false);
        }
        Contentfeild.setColumns(20);
        Contentfeild.setLineWrap(true);
        Contentfeild.setRows(5);
        Contentfeild.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 0, 255)));
        jScrollPane2.setViewportView(Contentfeild);

        Title.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
        Title.setText("Create a New File");
        if(file_type == 1)
        {
            Title.setText("View File");
        }
        if(file_type == 2)
        {
            Title.setText("Rename File");
        }
        if(file_type == 3)
        {
            Title.setText("Edit File");
        }
        if(file_type == 4)
        {
            Title.setText("Delete File");
        }

        Error_text.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
        Error_text.setForeground(new java.awt.Color(255, 0, 0));
        Error_text.setText("Error Feild");
        Error_text.setVisible(false);

        if(file_type == 1 || file_type == 2 || file_type ==3||file_type == 4)
        {
            FileNamefeild.setText(title);
            if(file_type == 1 || file_type == 3|| file_type== 4)
            {
                FileNamefeild.setEditable(false);
            }
        }

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(27, 27, 27)
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 464, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jPanel1Layout.createSequentialGroup()
                                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                            .add(jLabel1)
                                            .add(jLabel2))
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(FileNamefeild, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 387, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(169, 169, 169)
                                .add(Title)))
                        .add(0, 25, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, Error_text, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(8, 8, 8)
                .add(Title)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(FileNamefeild, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 278, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(5, 5, 5)
                .add(Error_text, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Save");
        if(file_type==1)
        {
            jButton1.setText("OK");
        }
        if(file_type ==2)
        {
            jButton1.setText("Rename");
        }
        if(file_type ==4)
        {
            jButton1.setText("Delete");
        }
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(143, 143, 143)
                .add(jButton2)
                .add(56, 56, 56)
                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(163, Short.MAX_VALUE))
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(0, 0, 0)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(0, 0, 0)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(461, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton2)
                    .add(jButton1))
                .addContainerGap())
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(36, 36, 36)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(36, 36, 36)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
//The save, okay, delete (accept) button has been pressed.
//If the File type is 0 - Create the file
//If the File type is 1 - View the file
//If the file type is 2 - Rename the file
//If the File type is 3 - edit the file
//If the file type is 4 - delete the file
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String Omessage = new String();
            
            if (file_type == 4) {
               Omessage = "DELETE" + divider + title + divider + temp.getUserName() + divider;
        //        outToServer.writeObject("DELETE" + divider + title + divider + temp.getUserName() + divider);//“DELETE” space filename space username newline
            }
            if (file_type == 3) {
                Omessage = "EDIT" + divider + title + divider + Contentfeild.getText() + divider + temp.getUserName() + divider;
          //      outToServer.writeObject("EDIT" + divider + title + divider + Contentfeild.getText() + divider + temp.getUserName() + divider);//“EDIT” space filename space new_content space username newline
            }
            if (file_type == 2) {
                Omessage = "CLOSE" + divider + title + divider + temp.getUserName();
            //    outToServer.writeObject("CLOSE" + divider + title + divider + temp.getUserName());
                Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,Omessage);
                Omessage = "RENAME" + divider + title + divider + FileNamefeild.getText() + divider + temp.getUserName() + divider;
           //     outToServer.writeObject("RENAME" + divider + title + divider + FileNamefeild.getText() + divider + temp.getUserName() + divider); //“RENAME” space old_filename space new_filename space username newline             
            }
            if (file_type == 1) {
                //Already viewed.
            }
            if (file_type == 0) {
                Omessage = "CREATE" + divider + FileNamefeild.getText() + divider + Contentfeild.getText() + divider + temp.getUserName();
           //     outToServer.writeObject("CREATE" + divider + FileNamefeild.getText() + divider + Contentfeild.getText() + divider + temp.getUserName());
            }
        
            //If view is called we don't need to read anything more.
            if(file_type!=1)
            chunks = Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,Omessage).split(divider);
//If the request was True or view was called(always true)
        if (file_type==1 || chunks[0].equals("T")) {
                if (file_type == 0) {
                    System.out.println("File Created");
                    chunks[1]=Message;
                } else if (file_type == 1) {
                    System.out.println("View file allowed");
                } else if (file_type == 2) {
                    System.out.println("Rename File allowed");
                } else if (file_type == 3) {
                    System.out.println("Edit file allowed");
                } else if (file_type == 4) {
                    System.out.println("File Deleted");
                }
                
                //Unlock the current file so others can do stuff to it.
                //if(file_type==2)
                  //  outToServer.writeObject("CLOSE" + divider + title + divider + temp.getUserName());
                    //Acknowledgment that it was unlocked correctly
                    chunks = Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"CLOSE" + divider + title + divider + temp.getUserName()).split(divider);
                    if (chunks[0].equals("T")) {
                        System.out.println("Unlocked File");
                        this.setVisible(false);
                    } else {
                        System.out.println("Unlocked File - Fail");
                    }
            }
        else {
            //If any of the requests failed, a specified message will be outputted to user.
            Error_text.setText(chunks[1]);
            Error_text.setVisible(true);
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    
    //Cancel button has been pressed.
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.setVisible(false);
        
                //Unlock current file
                //outToServer.writeObject("CLOSE" + divider + title + divider + temp.getUserName());//“CLOSE”space filename space username newline
                chunks = Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"CLOSE" + divider + title + divider + temp.getUserName()).split(divider);
                if (chunks[0].equals("T")) {
                    System.out.println("Unlocked File");
                }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jPanel1MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseMoved
    }//GEN-LAST:event_jPanel1MouseMoved

    /**
     * @param args the command line arguments
     */
    public static void main(final User temp1, final ObjectOutputStream outToServer1, final ObjectInputStream inFromServer1, final int File_type, final String file_message, final String file_title, final Socket clientSocket1) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(File_viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(File_viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(File_viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(File_viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                temp = temp1;
                outToServer = outToServer1;
                inFromServer = inFromServer1;
                file_type = File_type; //0 = new file, 1 = view file, 2 = edit file. 3 = rename file
                Message = file_message;
                title = file_title;
                clientSocket = clientSocket1;
                new File_viewer().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea Contentfeild;
    private javax.swing.JLabel Error_text;
    private javax.swing.JTextField FileNamefeild;
    private javax.swing.JLabel Title;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
